//
//  IdolPickerView.swift
//  puretennis
//
//  Created by IYE Technologies on 11/21/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class IdolPicker: AbstractPickerView {

    var idolPicker = UIPickerView();
    
    var selecedIdol:NSDictionary!;
    
    var idols:[NSDictionary]  = [];
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder);
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame);
        self.idolPicker.frame = CGRect(x: margin, y: margin, width: self.frame.width - margin * 2, height: self.frame.height - margin * 2);
        self.idolPicker.dataSource = self;
        self.idolPicker.delegate = self;
        self.contentView.addSubview(self.idolPicker);
        self.loadIdols();
    }
    
    func loadIdols(){
        var noneIdol = NSMutableDictionary();
        noneIdol.setObject("", forKey: "guid");
        noneIdol.setObject("我的偶像", forKey: "name");
        self.idols.append(noneIdol);
        let url = "/api/v1/idols"
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var idols = response as [NSDictionary];
            for idol in idols {
                self.idols.append(idol);
            }
            self.idolPicker.reloadAllComponents();
            self.idolPicker.selectRow(0, inComponent: 0, animated: false);
            self.selecedIdol = self.idols.first;
            self.sendActionsForControlEvents(UIControlEvents.ValueChanged);
            }, errorHandle: { (error) -> Void in
                Utils.debug("Load idols failed error[\(error)]");
        });
    }
    
    func selectIdol(idolGuid:String){
        for(var i = 0; i < self.idols.count; i++){
            var currentIdol = self.idols[i] as NSDictionary;
            var guid = currentIdol.objectForKey("guid") as String;
            if(guid == idolGuid){
                self.selecedIdol = currentIdol;
                self.idolPicker.selectRow(i, inComponent: 0, animated: false);
            }
        }
    }
    
    override func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1;
    }
    
    override func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return self.idols.count;
    }
    
    func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
        var idol = self.idols[row];
        var name = idol.objectForKey("name") as String;
        var label = UILabel();
        label.font = Utils.fontHupo(18);
        label.textColor = UIColor.whiteColor();
        label.text = name;
        label.sizeToFit();
        return label;
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.selecedIdol = self.idols[row];
    }
    
}
